from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import document
from waveapi import robot_abstract
from waveapi import simplejson as json

import string
import logging


def AddGadget( properties, context ):

    root_wavelet = context.GetRootWavelet()
    root_blip = context.GetBlipById( root_wavelet.GetRootBlipId() )
    waveid = context.GetWaves()[0].GetId()
    gadget_arguments = {'waveid' : waveid}
    googlecode_prefix = 'http://debatewave.googlecode.com/svn/trunk/gadgets'
    gadget_address = googlecode_prefix + '/participantAdder-test.xml'
    debatewise_gadget = document.Gadget( gadget_address, gadget_arguments )

    root_blip.GetDocument().AppendElement( debatewise_gadget )


def GadgetEventHandler( properties, context ):
    logging.debug( 'GadgetEventHandler hit' )
    # get the event context data from the current wave and its resident gadget
    root_wavelet = context.GetRootWavelet()
    root_blip = context.GetBlipById( root_wavelet.GetRootBlipId() )
    waveid = context.GetWaves()[0].GetId()

    participant_polling_gadget = None
    try:
        participant_polling_gadget = [x for x in root_blip.GetElements().values() if x.type == document.ELEMENT_TYPE.GADGET][0]
        #TODO: validate gadget URL
    except:
        logging.debug( 'Failed to find the resident gadget. This should not generally happen.' )

    new_participant_sets_count = int( participant_polling_gadget.get( 'new_participant_sets_count', '0' ) )
    if new_participant_sets_count > 0:
        new_participants_sets_json = participant_polling_gadget.get( 'new_participants_sets_json', '' )
        logging.debug( 'new_participants_sets_json:' + new_participants_sets_json )
        new_participants_sets = json.loads( new_participants_sets_json )
        logging.debug( 'new_participants_sets loaded into json:' + json.dumps( new_participants_sets ) )
        #new_participants_sets_debug_output = '\n'.join( [l.rstrip() for l in new_participants_sets.splitlines()] )

        root_wavelet.CreateBlip().GetDocument().SetText( "Found Participants Sets:" + json.dumps( new_participants_sets ) )
        for participant_set in new_participants_sets:
            logging.debug( 'my wave_id="' + waveid + '", participant_set["waveid"]="' + participant_set['waveid'] + '"' )
            for participant in participant_set['participants'].split( ',' ):
                root_wavelet.AddParticipant( participant )
                root_wavelet.CreateBlip().GetDocument().SetText( "Added " + participant )
                #root_wavelet.CreateBlip().GetDocument().SetText( "Iterated set: wave_id=" + wave_id + ",participants=" + participants )
            #TODO: Clear from DB

        root_wavelet.CreateBlip().GetDocument().SetText( "Done iterating" )
        #TODO: Clear from shared state
        #debatewise_gadget.SubmitDelta( {'requesttype' : 0} )


if __name__ == '__main__':
    debatewise_robot = robot.Robot( 'debatewise-adder',
        image_url = 'http://aleksei-testbot.appspot.com/assets/icon.png',
        version = '13',
        profile_url = 'http://aleksei-testbot.appspot.com/' )

    debatewise_robot.RegisterHandler( events.WAVELET_SELF_ADDED, AddGadget )
    debatewise_robot.RegisterHandler( events.BLIP_SUBMITTED, GadgetEventHandler )

    debatewise_robot.Run()
